package com.dadao.learn;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MybatisUtil {
    //对外只开放一个工厂
    public static final SqlSessionFactory SSF = createSqlSessionFactory();
    //声明一个线程变量
    public static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    //1.获得会话工厂
    private static SqlSessionFactory createSqlSessionFactory() {
        try {
            //读取配置文件
            Reader reader = Resources.getResourceAsReader("configuration.xml");
            //创建会话工厂构建类对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //构建会话工厂
            return builder.build(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //2.获得会话
    public static SqlSession getSession() {
        if (THREAD_LOCAL.get() == null) {
            SqlSession session = SSF.openSession();
            THREAD_LOCAL.set(session);
        }
        return THREAD_LOCAL.get();
    }

    public static void close() {
        if (THREAD_LOCAL.get() != null) {
            SqlSession session = THREAD_LOCAL.get();
            session.close();
            THREAD_LOCAL.remove();
        }
    }
}
